<script setup lang="ts">
import { commentPost, getPostDetail, likePost, unlikePost } from '@/api/post'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 帖子数据
const post = ref({
  id: 0,
  title: '',
  content: '',
  images: [],
  avatar: '',
  nickname: '',
  createdAt: '',
  likes: 0,
  commentCount: 0,
  views: 0,
  isLiked: false,
})

// 评论列表
const comments = ref([])

// 加载状态
const loading = ref(false)
const hasMore = ref(true)

// 评论输入
const commentText = ref('')
const replyTo = ref<any>(null)

// 格式化时间
function formatTime(time: string) {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }

  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }

  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }

  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }

  // 大于30天
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 预览图片
function previewImage(images: string[], current: number) {
  uni.previewImage({
    urls: images,
    current: images[current],
  })
}

// 点赞/取消点赞
async function toggleLike() {
  try {
    if (post.value.isLiked) {
      await unlikePost(post.value.id)
      post.value.likes--
    }
    else {
      await likePost(post.value.id)
      post.value.likes++
    }
    post.value.isLiked = !post.value.isLiked
  }
  catch (error) {
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none',
    })
  }
}

// 评论点赞/取消点赞
function toggleCommentLike(comment: any) {
  comment.isLiked = !comment.isLiked
  comment.likes += comment.isLiked ? 1 : -1
}

// 分享帖子
function sharePost() {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  })
}

// 回复评论
function replyComment(comment: any, reply?: any) {
  replyTo.value = reply || comment
  // 聚焦输入框
  uni.pageScrollTo({
    selector: '.comment-input',
    duration: 300,
  })
}
// 递归查找顶层评论
function findRootComment(commentId) {
  const comment = comments.value.find(c => c.id === commentId)
  if (!comment || !comment.parentId)
    return comment
  return findRootComment(comment.parentId)
}
// 提交评论
async function submitComment() {
  if (!commentText.value.trim()) {
    return
  }

  try {
    const res = await commentPost(post.value.id, {
      content: commentText.value,
      parentId: replyTo.value?.id,
    })

    const newComment = {
      id: res.data.id,
      content: res.data.content,
      avatar: res.data.user?.avatar || '/static/images/avatar.svg',
      nickname: res.data.user?.nickname || '当前用户',
      createdAt: res.data.createdAt,
      likes: 0,
      isLiked: false,
      replies: [],
    }

    if (replyTo.value) {
      // 回复评论

      const comment = findRootComment(replyTo.value.id)
      if (comment) {
        comment.replies = comment.replies || []
        comment.replies.unshift({
          id: res.data.id,
          content: res.data.content,
          user: res.data.user,
          replyTo: replyTo.value.user.nickname,
          createdAt: res.data.createdAt,
        })
      }
    }
    else {
      // 新增评论
      comments.value.unshift(newComment)
    }

    commentText.value = ''
    replyTo.value = null

    // 更新评论数
    post.value.commentCount++
  }
  catch (error) {
    uni.showToast({
      title: error.message || '评论失败',
      icon: 'none',
    })
  }
}

// 页面加载
onLoad((options) => {
  loading.value = true
  const postId = options?.id
  if (postId) {
    getPostDetail(postId).then((res) => {
      const data = res.data
      post.value = {
        id: data.id,
        title: data.title,
        content: data.content,
        images: data.images ? data.images.split(',') : [],
        avatar: data.user?.avatar || '/static/images/avatar.svg',
        nickname: data.user?.nickname || '未知用户',
        createdAt: data.createdAt,
        likes: data.likes || 0,
        commentCount: data.commentCount || 0,
        views: data.views || 0,
        isLiked: data.isLiked || false,
      }
      comments.value = data.comments || []
      // 扁平化n级评论
      comments.value.forEach((comment) => {
        comment.replies = flatReplies(comment.replies || [])
      })

      post.value.commentCount = comments.value.length
    }).catch(() => {
      loading.value = false
    })
  }
})
function flatReplies(replies) {
  return replies.reduce((acc, reply) => {
    acc.push(reply)
    if (reply.replies && reply.replies.length > 0) {
      acc = acc.concat(flatReplies(reply.replies))
    }
    return acc
  }, [])
}
</script>

<template>
  <view class="container">
    <!-- 帖子内容 -->
    <view class="post-content">
      <view class="post-header">
        <image class="avatar" src="../../../static/avatar.jpg" mode="aspectFill" />
        <view class="user-info">
          <view class="nickname">
            {{ post.nickname }}
          </view>
          <view class="time">
            {{ formatTime(post.createdAt) }}
          </view>
        </view>
      </view>

      <view class="content">
        <view class="title">
          {{ post.title }}
        </view>
        <view class="text">
          {{ post.content }}
        </view>
        <view v-if="post.images && post.images.length > 0" class="image-list">
          <image
            v-for="(image, index) in post.images"
            :key="index"
            :src="image"
            mode="aspectFill"
            @click="previewImage(post.images, index)"
          />
        </view>
      </view>

      <view class="post-footer">
        <view class="action-item" @click="toggleLike">
          <uni-icons :type="post.isLiked ? 'hand-up-filled' : 'hand-up'" size="24" color="#666" />
          <text class="count">
            {{ post.likes }}
          </text>
        </view>
        <view class="action-item">
          <uni-icons type="chat" size="24" color="#666" />
          <text class="count">
            {{ post.commentCount }}
          </text>
        </view>
        <view class="action-item" @click="sharePost">
          <uni-icons type="eye" size="24" color="#666" />
          <text class="count">
            {{ post.views }}
          </text>
        </view>
      </view>
    </view>

    <!-- 评论列表 -->
    <view class="comment-list">
      <view class="comment-title">
        评论 {{ post.commentCount }}
      </view>

      <view v-for="comment in comments.filter(c => !c.parentId)" :key="comment.id" class="comment-item">
        <image class="avatar" src="../../../static/avatar.jpg" mode="aspectFill" />
        <view class="comment-content">
          <view class="comment-header">
            <view class="nickname">
              {{ comment.user.nickname }}
            </view>
            <view class="time">
              {{ formatTime(comment.createdAt) }}
            </view>
          </view>
          <view class="text">
            {{ comment.content }}
          </view>
          <view class="comment-footer">
            <view class="action-item" @click="toggleCommentLike(comment)">
              <uni-icons :type="comment.isLiked ? 'hand-up-filled' : 'hand-up'" size="24" color="#666" />
              <text class="count">
                {{ comment.likes }}
              </text>
            </view>
            <view class="action-item" @click="replyComment(comment)">
              <uni-icons type="chat" size="24" color="#666" />
              <text class="count">
                回复
              </text>
            </view>
          </view>

          <!-- 回复列表 -->
          <view v-if="comment.replies && comment.replies.length > 0" class="reply-list">
            <view v-for="reply in comment.replies" :key="reply.id" class="reply-item">
              <view class="reply-header">
                <text class="nickname">
                  {{ reply.user.nickname }}
                </text>
                <text v-if="reply.replyTo" class="reply-to">
                  回复
                </text>
                <text v-if="reply.replyTo" class="nickname">
                  {{ reply.replyTo }}
                </text>
              </view>
              <view class="text">
                {{ reply.content }}
              </view>
              <view class="reply-footer">
                <view class="time">
                  {{ formatTime(reply.createdAt) }}
                </view>
                <view class="action-item" @click="replyComment(comment, reply)">
                  <uni-icons type="chat" size="24" color="#666" />
                  <text class="count">
                    回复
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="comments.length > 0" class="load-more">
        <text v-if="loading">
          加载中...
        </text>
        <text v-else-if="!hasMore">
          没有更多了
        </text>
      </view>

      <!-- 空状态 -->
      <view v-if="comments.length === 0 && !loading" class="empty">
        <image class="empty-icon" src="/static/images/empty.svg" mode="aspectFit" />
        <view class="empty-text">
          暂无评论
        </view>
      </view>
    </view>

    <!-- 评论输入框 -->
    <view class="comment-input">
      <input
        v-model="commentText"
        class="input"
        type="text"
        :placeholder="replyTo ? `回复 ${replyTo.user.nickname}` : '说点什么...'"
        @confirm="submitComment"
      >
      <view class="send-btn" :class="{ active: commentText.trim().length > 0 }" @click="submitComment">
        发送
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.post-content {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .post-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }

    .user-info {
      flex: 1;

      .nickname {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 6rpx;
      }

      .time {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .content {
    .title {
      font-size: 36rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 20rpx;
    }

    .text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 20rpx;
    }

    .image-list {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -10rpx;

      image {
        width: calc(33.33% - 20rpx);
        height: 200rpx;
        margin: 10rpx;
        border-radius: 8rpx;
      }
    }
  }

  .post-footer {
    display: flex;
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid #eee;

    .action-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;

      .iconfont {
        font-size: 36rpx;
        color: #999;
        margin-right: 10rpx;

        &.icon-like-filled {
          color: #4caf50;
        }
      }

      .count {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.comment-list {
  background: #fff;
  padding: 30rpx;

  .comment-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 30rpx;
  }

  .comment-item {
    display: flex;
    margin-bottom: 30rpx;

    .avatar {
      width: 64rpx;
      height: 64rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }

    .comment-content {
      flex: 1;

      .comment-header {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;

        .nickname {
          font-size: 28rpx;
          color: #333;
          margin-right: 20rpx;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }

      .text {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
        margin-bottom: 10rpx;
      }

      .comment-footer {
        display: flex;
        margin-bottom: 20rpx;

        .action-item {
          display: flex;
          align-items: center;
          margin-right: 30rpx;

          .iconfont {
            font-size: 32rpx;
            color: #999;
            margin-right: 10rpx;

            &.icon-like-filled {
              color: #4caf50;
            }
          }

          .count {
            font-size: 24rpx;
            color: #999;
          }
        }
      }

      .reply-list {
        background: #f8f8f8;
        border-radius: 8rpx;
        padding: 20rpx;

        .reply-item {
          margin-bottom: 20rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .reply-header {
            margin-bottom: 10rpx;

            .nickname {
              font-size: 26rpx;
              color: #333;
            }

            .reply-to {
              font-size: 26rpx;
              color: #999;
              margin: 0 10rpx;
            }
          }

          .text {
            font-size: 26rpx;
            color: #666;
            line-height: 1.6;
            margin-bottom: 10rpx;
          }

          .reply-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .time {
              font-size: 24rpx;
              color: #999;
            }

            .action-item {
              display: flex;
              align-items: center;

              .iconfont {
                font-size: 28rpx;
                color: #999;
                margin-right: 6rpx;
              }

              .count {
                font-size: 24rpx;
                color: #999;
              }
            }
          }
        }
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 30rpx 0;

  text {
    font-size: 24rpx;
    color: #999;
  }
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.comment-input {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #eee;

  .input {
    flex: 1;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    color: #333;
  }

  .send-btn {
    width: 120rpx;
    height: 72rpx;
    line-height: 72rpx;
    text-align: center;
    font-size: 28rpx;
    color: #999;
    margin-left: 20rpx;

    &.active {
      color: #4caf50;
    }
  }
}
</style>
